// pages/chat-detail/chat-detail.js
const messageDao = require('../../dao/messageDao')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listHeight: 350,
    _2openid: '100',
    _2name: '',
    // _openid: 'oDMFW5bP9r8KwM5xXv7C_kIWk-HM',
    _openid: '',
    message: [],
    messageId: '',
    value: '',
    topView: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let systemInfo = wx.getSystemInfoSync()
    let pxToRpxScale = 750 / systemInfo.windowWidth;
    this.setData({
      listHeight: systemInfo.windowHeight * pxToRpxScale - 120
    })
    this.setData({
      _2openid: options._2openid,
      _2name: options._2name,
      _openid: app.data.currentUser._openid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const _ = app.data.db.command
    messageDao.where(_.or([{
        _openid: this.data._openid,
        _2openid: this.data._2openid
      },
      {
        _openid: this.data._2openid,
        _2openid: this.data._openid
      }
    ])).then(res => {
      console.log(res)
      if (res.data[0]) {
        setTimeout(this.updateTopView, 100 )
        this.setData({
          message: res.data[0].message,
          messageId: res.data[0]._id
        })
      }

    })
  },

  /**
   * 首次进入界面，跳转到最底部
   */
  updateTopView() {
    let lenght = this.data.message.length - 1
    this.setData({
      topView: "item" + lenght
    })
  },

  /**
   * 1, 首次发消息，创建消息
   * 2，否则是，更新消息
   */
  bindSend() {
    if(!this.data.value) {
        return
    }
    let content = {
      content: this.data.value,
      sender: this.data._openid,
      createDate: new Date()
    }
    this.data.message.push(content)
    let lenght = this.data.message.length - 1
    this.setData({
      value: '',
      message: this.data.message,
      topView: "item" + lenght
    })
    if (this.data.messageId) {
      messageDao.update(this.data.messageId, {
        message: this.data.message
      }).then(res => {
        console.log(res)
      })
    } else {
      messageDao.add({
        _2openid: this.data._2openid,
        _2name: this.data._2name,
        _name: app.data.currentUser.name,
        message: this.data.message
      }).then(res => {
        console.log(res)
      })
    }

  },




  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})